<template>
  <view>
    <view style="display: flex; justify-content: center; margin: 20rpx 0">
      <view style="width: 50%">
        <uni-segmented-control
          :current="current"
          :values="items"
          :style-type="styleType"
          :active-color="activeColor"
          @clickItem="onClickItem"
        />
      </view>
    </view>

    <view v-if="current === 0">
      <view class="form">
        <view class="form-content">
          <view class="form-item">
            <text class="label">危废行业俗称:</text>
            <text class="iptClass">{{ memberStore.approval.wfTypeName }}</text>
          </view>

          <view class="form-item">
            <text class="label">预计转移时间:</text>
            <text class="iptClass">{{
              memberStore.approval.planTransTime
            }}</text>
          </view>
          <!-- <view class="form-item" style="border-top: 1rpx solid #ddd">
            <text class="label">转移总量</text>
            <text class="iptClass">{{
              memberStore.approval.wfTrans_Weight
            }}</text>
          </view> -->
          <view v-if="memberStore.approval.showWeight">
            <view
              class="form-item"
              v-for="item in memberStore.approval.weight"
              :key="item.wfType"
              style="border-bottom: 1rpx solid #ddd"
            >
              <text class="label">{{ `${item.wfTypeName}重量:` }}</text>
              <input
                class="iptClass"
                type="number"
                placeholder="请输入实际转运重量"
                v-model.trim="item.wfWeight"
              />
            </view>
          </view>

          <view class="form-item">
            <text class="label">去向:</text>
            <text class="iptClass">{{ memberStore.approval.transTo }}</text>
          </view>
          <ImageLogic :picturesPath="picturesPath" :isHide="true"></ImageLogic>
          <view class="form-item">
            <text class="label">备注:</text>
            <text class="iptClass">{{ memberStore.approval.remark }}</text>
          </view>
          <view class="form-item">
            <text class="label">申请人:</text>
            <text class="iptClass">{{ memberStore.approval.userName }}</text>
          </view>
          <view class="form-item">
            <text class="label">所属部门:</text>
            <text class="iptClass">{{ memberStore.approval.deptName }}</text>
          </view>
          <view class="form-item">
            <text class="label">转运单号:</text>
            <text class="iptClass">{{ memberStore.approval.transCode }}</text>
          </view>
          <view class="form-item">
            <text class="label">流程:</text>
          </view>
          <view
            class="listsClass"
            v-for="(item, index) in processLists"
            :key="index"
          >
            <view>
              <text class="mgr">审批人:{{ item.username }}</text>
              <text class="mgr"
                >环节:{{ item.wfOperationLogActivityName }}</text
              >
            </view>
            <view>
              <text>意见:{{ item.wfOperationLogHandleSuggestion }}</text>
              <text>日期:{{ item.wfOperationLogOperationTime }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-if="current === 1">
      <view class="overClass" style="height: 83vh">
        <view v-if="state.rows.length">
          <view v-for="item in state.rows" :key="item.id">
            <view class="wrapBox">
              <view class="smallBox">
                <text class="maxwidth">
                  危废行业俗称:{{ item.wfTypeName }}
                </text>
                <text> 容器/包装类型:{{ item.wfContainerType }} </text>
              </view>
              <view class="smallBox">
                <text> 去向:{{ item.wfTo }} </text>
                <text> 产出日期:{{ item.produce_Time }} </text>
              </view>
              <view class="smallBox">
                <!-- <text> 名称:{{ item.wfName }} </text> -->
                <text> 登记人:{{ item.registrant }} </text>
              </view>
              <!-- <view class="smallBox">
                <text> 废物类别:{{ item.wfTypeCode }} </text>
                <text> 危废代码:{{ item.wfCreateCode }} </text>
              </view> -->
              <!-- <view class="smallBox">
                <text> 产出量:{{ item.wfWeight }} </text>
                <text> 单位:{{ item.wfUnit }} </text>
              </view> -->
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="box">
      <button
        class="btn"
        style="color: white; margin-right: 20rpx"
        @click="handleSave"
        :disabled="Approved"
        :loading="Approved"
      >
        审批通过
      </button>
      <button
        class="commonBtn"
        @click="handlesBack"
        v-if="memberStore.approval.activityName != '提交申请'"
      >
        退回
      </button>
    </view>
    <l-popup :radius="20" :show="popupShow">
      <view style="width: 70vw; padding: 40rpx">
        <view class="uni-textarea">
          <textarea
            style="height: 200rpx"
            v-model.trim="suggestion"
            placeholder="填写退回意见"
          />
        </view>
        <view class="classBtn">
          <button
            class="sureClass"
            @click="handlebackSure"
            :disabled="isReturn"
            :loading="isReturn"
          >
            确定
          </button>
          <button class="commonBtn" @click="popupShow = false">取消</button>
        </view>
      </view>
    </l-popup>
  </view>
</template>

<script setup>
import lPopup from "@/uni_modules/l-popup/components/l-popup/l-popup.vue";
import {
  wf_flow_submit,
  select_register_by_ids,
  wfTypeFindPage,
  workflowReject,
  select_flow_detail,
  select_user_by_ids,
  update_trans_apply_weight,
} from "./index";
import { parseTime } from "@/utils";
import { useMemberStore } from "@/stores/modules/member";
const picturesPath = ref([]);
const current = ref(0);
const items = ref(["基本信息", "转运详情"]);
const styleType = ref("button");
const activeColor = ref("#007aff");
const memberStore = useMemberStore();
const popupShow = ref(false);
const suggestion = ref("");
const processLists = ref([]);
//审批通过
const Approved = ref(false);
//退回
const isReturn = ref(false);
const state = reactive({
  columns: [
    { name: "wfTypeName", title: "类型", fixed: true },
    { name: "wfName", title: "名称" },
    { name: "wfWeight", title: "产出量" },
    { name: "wfUnit", title: "单位" },
    { name: "produceTime", title: "产出日期" },
    { name: "wfContainerType", title: "容器/包装类型" },
    { name: "wfTypeCode", title: "废物类别" },
    { name: "wfCreateCode", title: "危废代码" },
    { name: "wfTo", title: "去向" },
  ],
  rows: [],
});
onLoad(async (e) => {
  const respage = await wfTypeFindPage();
  //获取危废行业俗称
  const typeLists = memberStore.approval.wfType.split(",");
  const TypeNames = [];
  memberStore.approval.weight = [];
  typeLists.forEach((wfType) => {
    const obj1 = respage.data.find((item) => item.id == wfType);
    if (obj1) {
      TypeNames.push(obj1.wfTypeName);
      if (memberStore.approval.showWeight) {
        memberStore.approval.weight.push({
          wfType: +wfType,
          wfTypeName: obj1.wfTypeName,
        });
      }
    }
  });
  memberStore.approval.wfTypeName = TypeNames.join(",");
  //获取危废行业俗称
  if (memberStore.approval.picture) {
    picturesPath.value = JSON.parse(memberStore.approval.picture);
  }
  const res = await select_register_by_ids(memberStore.approval.wfIds);
  state.rows = res.data;
  const createUserIds = state.rows.map((item) => item.createUserId);
  const idsStr1 = [...new Set(createUserIds)].join();
  const resids = await select_user_by_ids(idsStr1);
  const ress = await wfTypeFindPage();
  state.rows.forEach((item) => {
    const objone = resids.data.find((list) => list.userId == item.createUserId);
    if (objone) {
      item.registrant = objone.username;
    }
    item.produce_Time = parseTime(item.produceTime, "{y}-{m}-{d}");
    //获取危废行业俗称
    if (item.wfType) {
      const typeLists = item.wfType.split(",");
      const TypeNames = [];
      typeLists.forEach((wfType) => {
        const obj1 = ress.data.find((item) => item.id == wfType);
        if (obj1) {
          TypeNames.push(obj1.wfTypeName);
        }
      });
      item.wfTypeName = TypeNames.join(",");
    }
    //获取危废行业俗称
  });

  const result = await select_flow_detail(memberStore.approval.instanceId);
  processLists.value = JSON.parse(JSON.stringify(result.data));
  const ids = processLists.value.map((item) => item.wfOperationLogUserId);
  const res1 = await select_user_by_ids(ids);
  console.log(res, 3333333);
  processLists.value.forEach((item) => {
    const obj = res1.data.find(
      (list) => list.userId == item.wfOperationLogUserId
    );
    if (obj) {
      item.username = obj.username;
    }
    item.wfOperationLogOperationTime = parseTime(
      item.wfOperationLogOperationTime
    );
  });
});
const handleSave = async () => {
  const ishaswfWeight =
    memberStore.approval.weight.length &&
    memberStore.approval.weight.every((item) => !!item.wfWeight);
  if (
    memberStore.approval.showWeight &&
    (!ishaswfWeight || memberStore.approval.weight.length == 0)
  ) {
    return uni.showToast({
      icon: "none",
      title: "请输入实际转运重量",
    });
  }
  try {
    Approved.value = true;
    memberStore.approval.picture = JSON.stringify(picturesPath.value);
    const res = await wf_flow_submit(
      memberStore.approval.applyId,
      memberStore.approval.workitemId,
      memberStore.approval.applyDeptId
    );
    if (memberStore.approval.showWeight) {
      await update_trans_apply_weight(
        memberStore.approval.applyId,
        encodeURIComponent(JSON.stringify(memberStore.approval.weight))
      );
    }
    if (res.data) {
      uni.showToast({ icon: "success", title: "审批通过" });
      uni.switchTab({
        url: `/pages/index/index`,
      });
    }
  } finally {
    Approved.value = false;
  }
};
const handlesBack = () => {
  popupShow.value = true;
  suggestion.value = "";
};

const handlebackSure = async () => {
  // 接口的status报faild:ERR_UNESCAPED_CHARACTERS这个错误意思是请求路径包含未转义的字符 由于url中包含特殊字符（如中文字符或空格）或非英文数字造成的（http://www.imangodoc.com/4Ize1P30.html）
  try {
    isReturn.value = true;
    memberStore.approval.picture = JSON.stringify(picturesPath.value);
    await workflowReject(
      memberStore.approval.applyId,
      memberStore.approval.workitemId,
      memberStore.approval.applyDeptId,
      encodeURIComponent(suggestion.value)
    );
    uni.showToast({ icon: "success", title: "退回成功" });
    setTimeout(() => {
      uni.switchTab({
        url: `/pages/index/index`,
      });
    }, 400);
  } finally {
    isReturn.value = false;
  }
};
const onClickItem = (e) => {
  if (current.value !== e.currentIndex) {
    current.value = e.currentIndex;
  }
};
</script>

<style lang="scss" scoped>
.form {
  background-color: #f4f4f4;
  .form-content {
    height: 83vh;
    overflow-y: auto;
  }
  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      // width: 180rpx;
      white-space: nowrap;
      padding-right: 5rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
    position: fixed;
    bottom: 40rpx;
    width: 90%;
  }
  .flexClass {
    display: flex;
    justify-content: center;
  }
}
.box {
  position: fixed;
  display: flex;
  justify-content: center;
  bottom: 40rpx;
  width: 100vw;
  .btn {
    width: 30%;
    background-color: rgb(0, 122, 255);
    border-radius: 20rpx;
  }
}

.liucheng {
  display: flex;
  justify-content: space-around;
}
.mgr {
  margin-right: 20rpx;
}

.listsClass {
  line-height: 46rpx;
  padding: 25rpx 10rpx;
  background-color: #fff;
  font-size: 28rpx;
  border-bottom: 1rpx solid #ddd;
  view {
    display: flex;
    justify-content: space-between;
  }
}
</style>